<template>
  <div id="particles" class="particles">
    <!-- <div class="middle"> -->
    <div class="login-form">
      <div class="textwrapper">
        <h3 class="title">
          {{ $t('login.title') }}
        </h3>
        <div class="lang">
          <Lang />
        </div>
      </div>
      <el-form
        ref="formRef"
        size="default"
        class="elform"
        :rules="rules"
        :model="form"
      >
        <el-form-item prop="username">
          <el-input
            prefix-icon="User"
            type="text"
            autocomplete="off"
            :placeholder="$t('login.acc')"
            v-model="form.username"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="Lock"
            :placeholder="$t('login.pwd')"
            v-model="form.password"
            :type="passwordType"
          >
            <template v-slot:suffix>
              <i class="el-icon el-input__icon">
                <svg-icon
                  :icon="passwordType !== 'password' ? 'eye' : 'eye-close'"
                  @click="changeType"
                  class="mySvg"
                ></svg-icon>
              </i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="verifyCode">
          <el-input
            prefix-icon="Key"
            type="text"
            :placeholder="$t('login.ver')"
            style="width: 200px"
            v-model="form.verifyCode"
            clearable
          >
          </el-input>
          <div class="login-code">
            <el-image
              :src="verifyCodeImage"
              fit="contain"
              @click="updateVerifyCode"
              class="el-image"
            >
              <template #error>
                <div class="image-slot">
                  <img src="@/assets/defaultCodePic.jpg" />
                </div>
              </template>
            </el-image>
          </div>
        </el-form-item>
        <el-checkbox
          style="margin: 10px 10px 25px 0px; width: 78px"
          size="default"
          v-model="checked"
        >
          {{ $t('login.recordPwd') }}
        </el-checkbox>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%; height: 38px"
            @click="handleLogin"
            @keyup.enter="handleLogin"
            :loading="loading"
          >
            <span>{{ $t('login.btnTitle') }}</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- </div> -->
    <!-- 底部 -->
    <div class="footer">
      <div class="ga">
        <span>Copyright &copy; 2022 YS All Rights Reserved</span>
      </div>
      <div class="ga">
        <a href="https://beian.miit.gov.cn" target="_blank">
          <span class="mitt">辽ICP备2022009179号-1</span>
        </a>
      </div>
      <div class="ga">
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=21100402204079"
          target="_blank"
        >
          <img
            src="../../assets/备案图标.png"
            alt="policeIcon"
            style="width: 20px; height: 20px"
          />
          <span class="police">辽公网安备 21100402204079号</span>
        </a>
      </div>
      <!--   <div style="width: 300px; margin: 0 auto; padding: 20px 0">
        <a
          target="_blank"
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=21100402204079"
          style="
            display: inline-block;
            text-decoration: none;
            height: 20px;
            line-height: 20px;
          "
          ><img src="../../assets/备案图标.png" style="float: left" />
          <p
            style="
              float: left;
              height: 20px;
              line-height: 20px;
              margin: 0px 0px 0px 5px;
              color: #939393;
            "
          >
            辽公网安备 21100402204079号
          </p></a
        >
      </div> -->
    </div>
  </div>
</template>

<script setup>
import Lang from './component/lang.vue'
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import { useStore } from 'vuex'
import throttle from 'lodash/throttle'
import { updateVerifyCode as reAcquireCode } from '@/utils/auth.js'
import { login } from '@/api/login.js'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import '../../assets/js/jquery-1.11.1.min.js'
import '../../assets/js/jquery.particleground.min.js'

const router = useRouter()
const store = useStore()
const form = ref({
  username: '',
  password: '',
  verifyCode: ''
})

const checked = ref(false)
// 导入base64 使用base64对输入的密码加密
const base64 = require('js-base64').Base64

const loading = ref(false)
const verifyCodeImage = ref('/api/fmms/systemController/getVerifyCodeImage')

const updateVerifyCode = () => {
  verifyCodeImage.value = reAcquireCode()
}

const rules = ref({
  username: [
    { required: true, message: 'Please input AccountName', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input Password', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: 'Please input VerifyCode', trigger: 'blur' }
  ]
})

const formRef = ref(null)

onMounted(() => {
  particleground(document.getElementById('particles'), {
    dotColor: '#5cbdaa',
    lineColor: '#5cbdaa'
  })
  if (localStorage.getItem('username')) {
    form.value.username = localStorage.getItem('username')
    form.value.password = base64.decode(localStorage.getItem('password'))
    checked.value = true
  }
})

const handleLogin = throttle(() => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 验证通过后，判断是否勾选，如勾选则需要将密码加密后保存本地
      if (checked.value) {
        const secretByBase64 = base64.encode(form.value.password)
        localStorage.setItem('password', secretByBase64)
        localStorage.setItem('username', form.value.username)
      } else {
        localStorage.removeItem('password')
        localStorage.removeItem('username')
      }
      loading.value = true
      // 登录请求再vuex中发起，因此该处不在需要只需要派发login函数获取数据即可
      const res = await login(form.value)
      // console.log(res)
      if (res.code === 200) {
        localStorage.setItem('token', res.data.token)
        store.dispatch('app/login', res.data.token)
        // console.log(res.data.token)
        ElMessage({
          type: 'success',
          message: '登录成功',
          duration: 1500
        })
        loading.value = false
        // 登录成功后需要继续向后端发送请求获取菜单列表项（这块放在路由守卫中发送）
        // 跳转到首页
        router.push('/')
      } else {
        loading.value = false
        form.value.verifyCode = ''
        updateVerifyCode()
      }
    } else {
      loading.value = false
      console.log('error submit!!')
      return false
    }
  })
}, 500)

const passwordType = ref('password')
const changeType = () => {
  if (passwordType.value === 'password') {
    passwordType.value = 'text'
  } else {
    passwordType.value = 'password'
  }
}

function watchKeyup(e) {
  if (e.code === 'Enter') {
    handleLogin()
  } else {
    return false
  }
}

document.addEventListener('keyup', watchKeyup)

onBeforeUnmount(() => {
  document.removeEventListener('keyup', watchKeyup)
})

nextTick(() => {
  document.querySelector('.mitt').onmouseover = function () {
    this.style.color = 'red'
  }
  document.querySelector('.mitt').onmouseout = function () {
    this.removeAttribute('style')
  }
  document.querySelector('.police').onmouseover = function () {
    this.style.color = 'red'
  }
  document.querySelector('.police').onmouseout = function () {
    this.removeAttribute('style')
  }
})
</script>

<style lang="scss" scoped>
// @import '../../assets/css/style.css';
@media screen and (max-width: 603px) {
  .footer {
    flex-direction: column;
  }
}
* {
  margin: 0;
  padding: 0;
}
:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
.image-slot {
  width: 100%;
  height: 38px;
}

.particles {
  background: linear-gradient(303deg, #596ebd 10%, #6f86d6 80%);
  height: 100vh;
  position: relative;
}
.icon {
  width: 30px;
  height: 30px;
  background-color: yellow;
  position: absolute;
  margin: auto;
  margin-right: 20px;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.textwrapper {
  width: 310px;
  position: relative;
  padding: 0px 10px;
  height: 43px;
  .title {
    text-align: center;
    color: #333;
    font-size: 25px;
  }
  .lang {
    width: 25px;
    height: 25px;
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    cursor: pointer;
  }
}

// .middle {
.login-form {
  box-shadow: 0 20px 30px 0 rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  background-color: rgba(250, 250, 250, 0.8);
  border: 1px solid #fff;
  padding: 25px;
  z-index: 666;
  height: 330px;
  width: 330px;
  margin: auto;
  min-height: 330px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.elform {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  height: 260px;
  padding: 10px;
  &:deep(.el-input__inner) {
    height: 38px;
  }
  &:deep(.el-form-item) {
    margin-bottom: 20px;
  }
  &.elicon {
    display: inline-block;
    font-size: 12px;
    box-sizing: border-box;
    width: 40px;
    height: 38px;
    background-color: yellow;
  }
}

.login-code {
  margin-left: 10px;
  height: 38px;
  flex: 1;
  line-height: 38px;
  // float: right;
  .el-image {
    margin-top: 1px;
    height: 36px;
    cursor: pointer;
    border-radius: 3px;
    float: right;
  }
}
.input-icon {
  background-color: green;
  height: 38px;
  width: 14px;
  margin-left: 2px;
  color: #fff;
}
// }

.footer {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  text-align: center;
  // line-height: 80px;
  position: absolute;
  bottom: 10px;
  color: #fff;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 13px;
  letter-spacing: 1px;
  .ga {
    margin-right: 8px;
    display: flex;
    height: 25px;
    line-height: 25px;
    img {
      margin-top: -2px;
      vertical-align: middle;
      margin-right: 5px;
    }
  }
}
.mySvg:hover {
  cursor: pointer;
}
</style>
